/*
 * This program is free software; you can redistribute it and/or modify 
 * it under the terms of the GNU General Public License as published by 
 * the Free Software Foundation; either version 3 of the License, or 
 * (at your option) any later version.
 * 
 * This program is distributed in the hope that it will be useful, but 
 * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY 
 * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License 
 * for more details.
 * 
 * You should have received a copy of the GNU General Public License along 
 * with this program; if not, write to the Free Software Foundation, Inc., 
 * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
 */

#include <QFile>
#include <QFileInfo>
#include <QSettings>
#include <QRegExp>
#include "futabaagent.h"
#include "log.h"
#include "components/board.h"
#include "text.h"
#include "requestmanager.h"
#include "futabatasksendpost.h"

namespace Wishmaster
{
	FutabaAgent::FutabaAgent(const QString& host) : DefaultAgent(host),
		m_host(host)
	{
	}

	FutabaAgent::~FutabaAgent()
	{
	}


	void FutabaAgent::makePost(const PostDescriptor& post, const QString& captcha)
	{
		TaskPtr task = TaskPtr(new FutabaTaskSendPost(post, captcha, requestManager(), "Sending post", this));
		connect(task.data(), SIGNAL(result(TaskSendPost*,QByteArray,QString)), this, SLOT(resultPost(TaskSendPost*,QByteArray,QString)));
		m_pending[task->id()] = post.parent_thread;
		taskhub()->queueTask(task);
	}


	void FutabaAgent::createThread(const PostDescriptor& post, const QString& captcha)
	{
		TaskPtr task = TaskPtr(new FutabaTaskSendPost(post, captcha, requestManager(), "Creating thread", this));
		connect(task.data(), SIGNAL(result(TaskSendPost*,QByteArray,QString)), this, SLOT(resultPost(TaskSendPost*,QByteArray,QString)));
		m_pending[task->id()] = post.parent_thread;
		taskhub()->queueTask(task);
	}

	void FutabaAgent::deleteThread(const ThreadId& threadId, const QString& password)
	{
		log(llWarning, "Futallaby thread deletion is not implemented yet!!!");
	}

	void FutabaAgent::deletePost(const PostId& postId, const QString& password)
	{
		log(llWarning, "Futallaby post deletion is not implemented yet!!!");
	}

	void FutabaAgent::resultPost(TaskSendPost* task, const QByteArray& data, const QString& contentType)
	{
		auto it = m_pending.find(task->id());
		if(it == m_pending.end())
			return;
		ThreadId threadId = it->second;
		m_pending.erase(it);
		log(llDebug, "resultPost: %s:%d", qPrintable(threadId.chanName()), threadId.threadNumericId());
		//emit postingError("");
		emit postingDone(threadId);
		emit refresh(threadId, true);
	}

	QStringList FutabaAgent::ratings()
	{
		return QStringList();
	}

	ChanAgent* FutabaAgent::clone(const QString& host)
	{
		return new FutabaAgent(host);
	}

	QString FutabaAgent::id()
	{
		return "futallaby";
	}
}

Q_EXPORT_PLUGIN2(futabaagent, Wishmaster::FutabaAgent)
